<template>
  <div>
    <el-form ref="form" :rules="rules" :model="product" label-width="100px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="product.name"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="product.description"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="product.price"></el-input>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input v-model="product.stock"></el-input>
      </el-form-item>
      <el-form-item label="商品一级分类">
        <el-select
          v-model="product.categoryLevel1Id"
          placeholder="请选择商品一级分类"
          @change="onCategoryLevel1IdChange"
        >
          <el-option
            v-for="item in categoryLevel1"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="商品二级分类"
        v-if="product.categoryLevel1Id && categoryLevel2.length >= 1"
      >
        <el-select
          v-model="product.categoryLevel2Id"
          placeholder="请选择商品二级分类"
          @change="onCategoryLevel2IdChange"
        >
          <el-option
            v-for="item in categoryLevel2"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="商品三级分类"
        v-if="product.categoryLevel2Id && categoryLevel3.length >= 1"
      >
        <el-select
          v-model="product.categoryLevel3Id"
          placeholder="请选择商品三级分类"
        >
          <el-option
            v-for="item in categoryLevel3"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save()">保存</el-button>
        <el-button @click="back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "productAdd",
  data() {
    return {
      product: {
        id: "",
        name: "",
        description: "",
        price: "",
        stock: "",
        createDate: "",
        categoryLevel1Id: "",
        categoryLevel2Id: "",
        categoryLevel3Id: "",
      },
      categoryLevel1: [],
      categoryLevel2: [],
      categoryLevel3: [],
      pic: "",
      imageUrl: "",
      fileName: "",
      isUploadNew: false,
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [
          { required: true, message: "请正确输入商品价格", trigger: "blur" },
          {
            type: "number",
            message: "价格必须为数字",
            trigger: "blur",
            transform: (value) => Number(value),
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error("价格必须大于0"));
              } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
                callback(new Error("最多保留两位小数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        stock: [
          { required: true, message: "请正确输入商品库存", trigger: "blur" },
          {
            type: "number",
            message: "库存必须为整数",
            trigger: "blur",
            transform: (value) => Number(value),
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error("库存必须大于0"));
              } else if (!Number.isInteger(value)) {
                callback(new Error("库存必须是整数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    back() {
      this.$router.push("/managerIndex/manageProduct");
    },
    showInfo() {
      this.$axios
        .get(`api/product/find/${this.product.id}`)
        .then((response) => {
          this.product = response.data.product;
          // 确保正确设置图片URL
          if(this.product.fileName) {
            this.imageUrl = `http://192.168.1.146:8088/${this.product.fileName}`;
            this.fileName = this.product.fileName;
            console.log("图片路径"+this.imageUrl);
          }
          this.getCategoryLevel1();
          if(this.product.categoryLevel1Id) {
            this.getCategoryLevel2();
          }
          if(this.product.categoryLevel2Id) {
            this.getCategoryLevel3();
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    onCategoryLevel1IdChange() {
      console.log("一级分类的id" + this.product.categoryLevel1Id);
      // 清空二级和三级分类
      this.product.categoryLevel2Id = "";
      this.product.categoryLevel3Id = "";
      // 获取对应二级分类的所有数据
      this.getCategoryLevel2();
      this.categoryLevel3 = [];
    },
    onCategoryLevel2IdChange() {
      // 清空三级分类
      console.log("二级分类的id" + this.product.categoryLevel2Id);
      this.product.categoryLevel3Id = "";
      // 获取对应三级分类的所有数据
      this.getCategoryLevel3();
    },
    getCategoryLevel1() {
      this.$axios({
        url: "/api/category/getTypes1",
        method: "post",
      })
        .then((rs) => {
          this.categoryLevel1 = rs.data.list;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    getCategoryLevel2() {
      this.$axios({
        method: "post",
        data: {
          id: this.product.categoryLevel1Id,
        },
        url: "/api/category/getTypes2",
      })
        .then((rs) => {
          this.categoryLevel2 = rs.data.list;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    getCategoryLevel3() {
      this.$axios({
        method: "post",
        data: {
          id: this.product.categoryLevel2Id,
        },
        url: "/api/category/getTypes3",
      })
        .then((rs) => {
          this.categoryLevel3 = rs.data.list;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          this.$message.error('请检查表单填写是否正确');
          return false;
        }

        const formData = new FormData();
        if (this.product.categoryLevel1Id == "") {
          this.$message.error("请选择商品一级分类！");
          return;
        }
        if (this.product.categoryLevel2Id == "") {
          this.product.categoryLevel2Id = 0;
        }
        if (this.product.categoryLevel3Id == "") {
          this.product.categoryLevel3Id = 0;
        }
        formData.append("id", this.product.id);
        formData.append("name", this.product.name);
        formData.append("description", this.product.description);
        formData.append("categoryLevel1Id", this.product.categoryLevel1Id);
        formData.append("categoryLevel2Id", this.product.categoryLevel2Id);
        formData.append("categoryLevel3Id", this.product.categoryLevel3Id);
        formData.append("createDate", this.product.createDate);
        formData.append("price", this.product.price);
        formData.append("stock", this.product.stock);
        // 修改图片处理逻辑
        if (this.pic) {
          formData.append("pic", this.pic);
        } else if (this.fileName) {
          // 如果没有上传新图片但有已有图片，发送fileName
          formData.append("fileName", this.fileName);
        } else {
          this.$message.error("请上传商品图片");
          return;
        }

        this.$axios
          .post("/api/product/edit", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((response) => {
            if (response.data.editStatus) {
              this.$message.success("修改成功");
              this.$router.push("/managerIndex/manageproduct");
            } else {
              this.$message.error("修改失败");
            }
          })
          .catch((error) => {
            this.$message.error("保存失败：" + error.message);
          });
      });
    },
    beforeAvatarUpload(file) {
      const fileType = file.type;
      console.log(fileType);
      let isTypeOK = true;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (
        fileType != "image/png" &&
        fileType != "image/jpeg" &&
        fileType != "image/webp"
      ) {
        isTypeOK = false;
        this.$message.error("上传商品图片只能是[jpg,png,webp]格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 2MB!");
      }
      this.pic = file;
      console.log(this.pic);
      this.isUploadNew = true;
      console.log("上传了新的图片");
      return isTypeOK && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      // 确保图片URL正确更新
      if(file && file.raw) {
        this.imageUrl = URL.createObjectURL(file.raw);
      }
      console.log("图片URL更新为:", this.imageUrl);
    },
  },
  mounted() {
    this.product.id = this.$route.query.id;
    this.showInfo();
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
